package com.gmall.search.service;

import com.gmall.common.result.Result;
import com.gmall.model.product.BaseTrademark;
import com.gmall.model.product.SkuInfo;
import com.gmall.model.product.dto.Category123IdNameDTO;
import com.gmall.model.search.Goods;
import com.gmall.product.feign.ProductApiFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ESSyncService {


    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ProductApiFeignClient productApiFeignClient;//Http 网络调用 超时时间3s，

    private Integer syncCount = 0;

    @Autowired
    ElasticsearchRestTemplate   elasticsearchRestTemplate;


    private final String HOT_SKU = "hot_sku";

    /**
     * 热点商品统计与同步
     * 每点击一次，热度+1，保存到Redis中
     * 每十次，同步到ES中
     * @param skuId
     * @return
     */
    public Result<Long> clickSku(Long skuId){
        Double score = redisTemplate.opsForZSet().incrementScore(HOT_SKU,skuId.toString(),1);

        //Double score = redisTemplate.opsForZSet().score(HOT_SKU, skuId.toString());
        if(score % 10 == 0){
            Goods goods = elasticsearchRestTemplate.get(skuId.toString(), Goods.class);
            //Math.round(3.4);Math.round(3.5);
            /*Math.ceil(3.5);
            Math.floor(3.5);*/
            goods.setHotScore(Math.round(score));
            elasticsearchRestTemplate.save(goods);
        }

        return Result.ok(Math.round(score));
    }
    /**
     * 每10秒执行一次
     * 启动时间 8:25
     * 到达了8:30  第一次同步  ，获取lastSyncDateTime 为空，获取的是全量数据，同步到ES
     * 记录lastSyncDateTime = 8：30
     *
     * 时间来到了8：35  第二次同步  ，获取lastSyncDateTime 为8：30，获取的是增量数据，在8：30 之后修改的数据，同步到ES
     *
     * 记录lastSyncDateTime = 8：35
     *
     * 修改SKU的某条数据 8：37
     * 时间来到了8：40  第三次同步  ，获取lastSyncDateTime 为8：35，获取的是增量数据，在8：35 之后修改的数据，一条，同步到ES
     *记录lastSyncDateTime = 8：40
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void syncDB2ES(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("当前时间:" + simpleDateFormat.format(new Date()));

        String lastSyncDateTime =(String) redisTemplate.opsForValue().get("lastSyncDateTime");

        Map searchMap = new HashMap<>();
        if(!StringUtils.isEmpty(lastSyncDateTime)){
            System.out.println("上次同步的时间:" + lastSyncDateTime);
            searchMap.put("lastSyncDateTime",lastSyncDateTime);//lastSyncDateTime 可能为空
        }

        List<SkuInfo> skuInfoListAfterDateTime =  productApiFeignClient.getSkuInfoListAfterDateTime(searchMap);

        System.out.println("同步数据:" + skuInfoListAfterDateTime);
        if(skuInfoListAfterDateTime!=null&&skuInfoListAfterDateTime.size()>0){
            skuInfoListAfterDateTime.forEach(skuInfo -> {

                Goods goods = new Goods();
                goods.setId(skuInfo.getId());
                goods.setCategory3Id(skuInfo.getCategory3Id());

                Result<Category123IdNameDTO> category123IdNameDTOResult
                        = productApiFeignClient.getCategory123IdNameDTO(skuInfo.getCategory3Id());
                if(category123IdNameDTOResult.isOk()){
                    Category123IdNameDTO category123IdNameDTO = category123IdNameDTOResult.getData();

                    goods.setCategory1Id(category123IdNameDTO.getCategory1Id());//2, 30, 192
                    goods.setCategory2Id(category123IdNameDTO.getCategory2Id());

                    goods.setCategory1Name(category123IdNameDTO.getCategory1Name());
                    goods.setCategory2Name(category123IdNameDTO.getCategory2Name());
                    goods.setCategory3Name(category123IdNameDTO.getCategory3Name());
                }

                goods.setTmId(skuInfo.getTmId());

                Result<BaseTrademark> trademarkResult
                        = productApiFeignClient.getTrademarkById(skuInfo.getTmId());

                if(trademarkResult.isOk()){
                    BaseTrademark trademark = trademarkResult.getData();
                    goods.setTmName(trademark.getTmName());
                    goods.setTmLogoUrl(trademark.getLogoUrl());
                }
                goods.setPrice(skuInfo.getPrice().doubleValue());
                goods.setCreateTime(skuInfo.getCreateTime());
                goods.setTitle(skuInfo.getSkuName());
                goods.setDefaultImg(skuInfo.getSkuDefaultImg());

                elasticsearchRestTemplate.save(goods);//新增或者更新
            });
        }
        System.out.println("同步到ES===================");

        System.out.println("保存最后同步的时间:" +simpleDateFormat.format(new Date()));
        redisTemplate.opsForValue().set("lastSyncDateTime",simpleDateFormat.format(new Date()));

    }
}
